//
//  ModifyStaffVC.m
//  ReceiptDelivery
//
//  Created by 吕晶 on 2020/9/22.
//  Copyright © 2020 吕晶. All rights reserved.
//

#import "ModifyStaffVC.h"
#import "DriverAddCell.h"
#import "StaffMainModel.h"
#import "AddStaffChooseGenderCell.h"
#import "AddStaffJurisdictionCell.h"

@interface ModifyStaffVC () <UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) StaffMainModel *staffModel;

@end

@implementation ModifyStaffVC

-(StaffMainModel *)staffModel {
    if (!_staffModel) {
        _staffModel = [StaffMainModel new];
    }
    return _staffModel;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH - NaviHeight - 64 - BottomHeight) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = Color_backgroundColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

-(UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenH - BottomHeight - NaviHeight - 64, ScreenW, 64+BottomHeight)];
        _bottomView.backgroundColor = HexColor(0xffffff);
        
        UIButton *saveBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, 10, _bottomView.nim_width - 60, 44)];
        [saveBtn setBackgroundColor:Color_ThemeColor];
        saveBtn.layer.masksToBounds = YES;
        saveBtn.layer.cornerRadius = 6;
        [saveBtn setTitle:@"保存" forState:0];
        [saveBtn setTitleColor:HexColor(0xffffff) forState:0];
        saveBtn.titleLabel.font = BoldFontOfSize(16);
        [saveBtn addTarget:self action:@selector(saveClick) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:saveBtn];
    }
    return _bottomView;
}

- (void)saveClick {
    [self requestForSave];
}

- (void)requestForSave {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if (!self.staffModel.name.length) {
        [MBProgressHUD leShowFailedHUD:self.view message:@"请填写姓名"];
        return;
    }else {
        [dic setObject:self.staffModel.name forKey:@"name"];
    }
    if (!self.staffModel.phone.length) {
        [MBProgressHUD leShowFailedHUD:self.view message:@"请填写手机号"];
        return;
    }else {
        [dic setObject:self.staffModel.phone forKey:@"phone"];
    }
    if (!self.staffModel.email.length) {
        [MBProgressHUD leShowFailedHUD:self.view message:@"请填写邮箱"];
        return;
    }else {
        [dic setObject:self.staffModel.email forKey:@"email"];
    }
    self.staffModel.sex = [self.staffModel.sex isEqualToString:@"1"] ? @"1" : @"2";
    [dic setObject:self.staffModel.sex forKey:@"sex"];
    if (self.staffModel.department.length) {
        [dic setObject:self.staffModel.department forKey:@"department"];
    }
    if (self.staffModel.position.length) {
        [dic setObject:self.staffModel.position forKey:@"position"];
    }
    __block BOOL haveAuth = NO;
    [self.staffModel.authArray enumerateObjectsUsingBlock:^(StaffAuthModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.status) {
            haveAuth = YES;
            [dic setObject:obj.Id forKey:@"auth"];
        }
    }];
    if (!haveAuth) {
        [MBProgressHUD leShowFailedHUD:self.view message:@"请选择权限"];
        return;
    }
    [dic setObject:self.Id forKey:@"id"];
    
    [HttpRequest PostWithApi:ReceiptDeliveryEditStaff params:dic progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            __weak_self;
            [MBProgressHUD leShowSuccessHUDAddedTo:self.view message:@"保存成功" delayOperation:^{
                [weakself.rt_navigationController popViewControllerAnimated:YES];
            }];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"修改";
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.bottomView];
    [self requestForEdit];
}

- (void)requestForEdit {
    [HttpRequest PostWithApi:ReceiptDeliveryGetEditStaffInfo params:@{@"id":self.Id} progress:^(NSProgress * _Nonnull progress) {

    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            self.staffModel = [StaffMainModel mj_objectWithKeyValues:[responseObject objectForKey:@"user"]];
            [self.tableView reloadData];
            [self requestForAuth];
        }
    } fail:^(NSError * _Nonnull error) {

    }];
}

- (void)requestForAuth {
    [HttpRequest PostWithApi:ReceiptDeliveryStaffAuth params:@{} progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            self.staffModel.authArray = [StaffAuthModel mj_objectArrayWithKeyValuesArray:responseObject];
            [self.staffModel.authArray enumerateObjectsUsingBlock:^(StaffAuthModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                obj.status = NO;
                if (self.Id.length) {
                    if ([obj.Id isEqualToString:self.staffModel.auth]) {
                        obj.status = YES;
                    }
                }
            }];
            [self.tableView reloadData];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 6;
    }
    return self.staffModel.authArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 5) {
            AddStaffChooseGenderCell *cell = [AddStaffChooseGenderCell AddStaffChooseGenderCellWithTableView:tableView];
            cell.isMan = [self.staffModel.sex isEqualToString:@"1"] ? YES : NO;
            cell.showLine = NO;
            __weak_self;
            cell.changeBlock = ^{
                if ([weakself.staffModel.sex isEqualToString:@"1"]) {
                    weakself.staffModel.sex = @"2";
                }else {
                    weakself.staffModel.sex = @"1";
                }
                [weakself.tableView reloadData];
            };
            return cell;
        }else {
            DriverAddCell *cell = [DriverAddCell DriverAddCellWithTableView:tableView];
            if (indexPath.row == 0) {
                cell.titleText = @"姓名";
                cell.showLine = YES;
                cell.canClick = NO;
                cell.isMust = YES;
                cell.contentText = self.staffModel.name;
                __weak_self;
                cell.cellBlock = ^(NSString * _Nonnull str) {
                    weakself.staffModel.name = str;
                };
            }else if (indexPath.row == 1) {
                cell.titleText = @"手机号";
                cell.showLine = YES;
                cell.canClick = NO;
                cell.isMust = YES;
                cell.contentText = self.staffModel.phone;
                __weak_self;
                cell.cellBlock = ^(NSString * _Nonnull str) {
                    weakself.staffModel.phone = str;
                };
            }else if (indexPath.row == 2) {
                cell.titleText = @"邮箱";
                cell.showLine = YES;
                cell.canClick = NO;
                cell.isMust = YES;
                cell.contentText = self.staffModel.email;
                __weak_self;
                cell.cellBlock = ^(NSString * _Nonnull str) {
                    weakself.staffModel.email = str;
                };
            }else if (indexPath.row == 3) {
                cell.titleText = @"部门";
                cell.showLine = YES;
                cell.canClick = NO;
                cell.isMust = NO;
                cell.contentText = self.staffModel.department;
                __weak_self;
                cell.cellBlock = ^(NSString * _Nonnull str) {
                    weakself.staffModel.department = str;
                };
            }else if (indexPath.row == 4) {
                cell.titleText = @"岗位";
                cell.showLine = YES;
                cell.canClick = NO;
                cell.isMust = NO;
                cell.contentText = self.staffModel.position;
                __weak_self;
                cell.cellBlock = ^(NSString * _Nonnull str) {
                    weakself.staffModel.position = str;
                };
            }
            return cell;
        }
    }else {
        AddStaffJurisdictionCell *cell = [AddStaffJurisdictionCell AddStaffJurisdictionCellWithTableView:tableView];
        StaffAuthModel *model = self.staffModel.authArray[indexPath.row];
        cell.title = model.name;
        cell.showLine = YES;
        cell.isCan = model.status;
        __weak_self;
        cell.changeBlock = ^{
            model.status = !model.status;
            if (model.status) {
                [weakself.staffModel.authArray enumerateObjectsUsingBlock:^(StaffAuthModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (![obj.Id isEqualToString:model.Id]) {
                        obj.status = NO;
                    }
                }];
            }
            [tableView reloadData];
        };
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 5) {
            AddStaffChooseGenderCell *cell = [AddStaffChooseGenderCell AddStaffChooseGenderCellWithTableView:tableView];
            return cell.height;;
        }
        DriverAddCell *cell = [DriverAddCell DriverAddCellWithTableView:tableView];
        return cell.height;
    }
    AddStaffJurisdictionCell *cell = [AddStaffJurisdictionCell AddStaffJurisdictionCellWithTableView:tableView];
    return cell.height;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 10)];
        view.backgroundColor = Color_backgroundColor;
        return view;
    }
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 40)];
    view.backgroundColor = Color_backgroundColor;
    UILabel *lab1 = [UILabel new];
    lab1.text = @"*";
    lab1.textColor = HexColor(0xF35959);
    lab1.font = [UIFont systemFontOfSize:12];
    [lab1 sizeToFit];
    lab1.nim_left = 15;
    lab1.nim_top = 20;
    [view addSubview:lab1];
    UILabel *lab2 = [UILabel new];
    lab2.text = @"使用权限";
    lab2.textColor = HexColor(0x9C9DB3);
    lab2.font = [UIFont systemFontOfSize:12];
    [lab2 sizeToFit];
    lab2.nim_left = 3 + lab1.nim_right;
    lab2.nim_top = 20;
    [view addSubview:lab2];
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 10;
    }
    return 40;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 1) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 10)];
        view.backgroundColor = Color_backgroundColor;
        return view;
    }
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 1) {
        return 10;
    }
    return 0;
}

@end
